<?php
if(!defined('IN_XLR')) {
	exit('Access Denied');
}

function get_db() {
	global $_SGLOBAL, $_CONFIG;
	if(empty($_SGLOBAL['m_db'])) {
       $_SGLOBAL['single_db'] = new ezSQL_mysql('root','Ngjj1917','xunlianri','localhost','utf-8');
	}
	return $_SGLOBAL['single_db'];
}

//数据库连接
function master_db() {
	global $_SGLOBAL, $_CONFIG;
	if(empty($_SGLOBAL['m_db'])) {
		$_SGLOBAL['m_db'] = new dbstuff;
		$_SGLOBAL['m_db']->charset = $_CONFIG['m_dbcharset'];
		$_SGLOBAL['m_db']->connect($_CONFIG['m_dbhost'], $_CONFIG['m_dbuser'], $_CONFIG['m_dbpw'], $_CONFIG['m_dbname'], $_CONFIG['m_pconnect']);
	}
	return $_SGLOBAL['m_db'];
}

function slave_db() {
	global $_SGLOBAL, $_CONFIG;
	if(DB_COULD==0){
		return master_db();
	}
	if(empty($_SGLOBAL['s_db'])) {
		$_SGLOBAL['s_db'] = new dbstuff;
		$_SGLOBAL['s_db']->charset = $_CONFIG['s_dbcharset'];
		$_SGLOBAL['s_db']->connect($_CONFIG['s_dbhost'], $_CONFIG['s_dbuser'], $_CONFIG['s_dbpw'], $_CONFIG['s_dbname'], $_CONFIG['s_pconnect']);
	}
	return $_SGLOBAL['s_db'];
}

function master_db_close() {
	global $_SGLOBAL, $_CONFIG;
	if(!empty($_SGLOBAL['m_db'])) $_SGLOBAL['m_db']->close();
}

function slave_db_close() {
	global $_SGLOBAL, $_CONFIG;
	if(!empty($_SGLOBAL['s_db'])) $_SGLOBAL['s_db']->close();
}

//告警函数
function api_alarm($str) {
	global $_SGLOBAL, $_CONFIG;
	api_log("[ALARM] 告警信息: $str");
	$sms_mobile = $_CONFIG['alarm_admin_mobile'];
	$sql = "SELECT count(id) as count_number FROM logs WHERE create_time > $_SGLOBAL[timestamp] - $_CONFIG[alarm_covertime] AND info LIKE '[ALARM]%'";
	$query = slave_db()->query($sql);
	$log_count = slave_db()->fetch_array($query);
	if($log_count["count_number"] == 0){
		//间隔5分钟发送短信告警一次
		cn_sendSMS($sms_mobile, $str);
	}
}

//日志记录函数
function api_log($str) {

	// if(D_BUG && D_BUG_LOG2DB){
	// 	error_log2db($str);
	// }else if(D_BUG){
	// 	error_log($str); 
	// }
	
}

//日志记录到数据库
function error_log2db($str) {
	global $_SGLOBAL, $_CONFIG;
	$str = saddslashes($str);
	$sql = "INSERT INTO logs (info, create_time) VALUE ('$str', $_SGLOBAL[timestamp])";
	$query = master_db()->query($sql,  'SILENT');
}

//日志记录函数
function api_log2file($str) {
	//写文件记录Log
	global $_SGLOBAL, $_CONFIG;
	if(D_BUG){
	if(!is_dir(dirname($_CONFIG['api_log']))){
		mkdir(dirname($_CONFIG['api_log']));
	}
	file_put_contents($_CONFIG['api_log'], date('[d-M-Y H:i:s] ') . $str . "\r\n", FILE_APPEND);
	}
}

//SQL ADDSLASHES
function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

//去掉slassh
function sstripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = sstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

//获取在线IP
function getonlineip($format=0) {
	global $_SGLOBAL;

	if(empty($_SGLOBAL['onlineip'])) {
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
		$_SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	}
	if($format) {
		$ips = explode('.', $_SGLOBAL['onlineip']);
		for($i=0;$i<3;$i++) {
			$ips[$i] = intval($ips[$i]);
		}
		return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
	} else {
		return $_SGLOBAL['onlineip'];
	}
}

//获取到表名
function tname($name) {
	global $_CONFIG;
	return $_CONFIG['tablepre'].$name;
}

//时间格式化
function sgmdate($dateformat, $timestamp='', $format=0) {
	global $_CONFIGONFIG, $_SGLOBAL;
	if(empty($timestamp)) {
		$timestamp = $_SGLOBAL['timestamp'];
	}
	$timeoffset = strlen($_SGLOBAL['member']['timeoffset'])>0?intval($_SGLOBAL['member']['timeoffset']):intval($_CONFIGONFIG['timeoffset']);
	$result = '';
	if($format) {
		$time = $_SGLOBAL['timestamp'] - $timestamp;
		if($time > 24*3600) {
			$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
		} elseif ($time > 3600) {
			$result = intval($time/3600).lang('hour').lang('before');
		} elseif ($time > 60) {
			$result = intval($time/60).lang('minute').lang('before');
		} elseif ($time > 0) {
			$result = $time.lang('second').lang('before');
		} else {
			$result = lang('now');
		}
	} else {
		$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
	}
	return $result;
}

//字符串时间化
function sstrtotime($string) {
	global $_SGLOBAL, $_CONFIGONFIG;
	$time = '';
	if($string) {
		$time = strtotime($string);
		if(gmdate('H:i', $_SGLOBAL['timestamp'] + $_CONFIGONFIG['timeoffset'] * 3600) != date('H:i', $_SGLOBAL['timestamp'])) {
			$time = $time - $_CONFIGONFIG['timeoffset'] * 3600;
		}
	}
	return $time;
}

//ob
function obclean() {
	global $_CONFIG;

	ob_end_clean();
	if ($_CONFIG['gzipcompress'] && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

//处理搜索关键字
function stripsearchkey($string) {
	$string = trim($string);
	$string = str_replace('*', '%', addcslashes($string, '%_'));
	$string = str_replace('_', '\_', $string);
	return $string;
}

//连接字符
function simplode($ids) {
	return "'".implode("','", $ids)."'";
}

//格式化大小函数
function formatsize($size) {
	$prec=3;
	$size = round(abs($size));
	$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
	if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
	$unit = min(4, floor(log($size)/log(2)/10));
	$size = $size * pow(2, -10*$unit);
	$digi = $prec - 1 - floor(log($size)/log(10));
	$size = round($size * pow(10, $digi)) * pow(10, -$digi);
	return $size.$units[$unit];
}

//获取文件内容
function sreadfile($filename) {
	$content = '';
	if(function_exists('file_get_contents')) {
		@$content = file_get_contents($filename);
	} else {
		if(@$fp = fopen($filename, 'r')) {
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}

//写入文件
function swritefile($filename, $writetext, $openmod='w') {
	if(@$fp = fopen($filename, $openmod)) {
		flock($fp, 2);
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	} else {
		runlog('error', "File: $filename write error.");
		return false;
	}
}

//产生随机字符
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	if($numeric && substr($hash, 0, 1)=="0"){
		$hash = substr($hash, 1, strlen($hash)-1)."0";
	}
	return $hash;
}

//判断字符串是否存在
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}

//获取文件名后缀
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

//编码转换
function siconv($str, $out_charset, $in_charset='') {
	global $_CONFIG;

	$in_charset = empty($in_charset)?strtoupper($_CONFIG['charset']):strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);
	if($in_charset != $out_charset) {
		if (function_exists('iconv') && (@$outstr = iconv("$in_charset//IGNORE", "$out_charset//IGNORE", $str))) {
			return $outstr;
		} elseif (function_exists('mb_convert_encoding') && (@$outstr = mb_convert_encoding($str, $out_charset, $in_charset))) {
			return $outstr;
		}
	}
	return $str;//转换失败
}

//重新组建
function renum($array) {
	$newnums = $nums = array();
	foreach ($array as $id => $num) {
		$newnums[$num][] = $id;
		$nums[$num] = $num;
	}
	return array($nums, $newnums);
}

//截取链接
function sub_url($url, $length) {
	if(strlen($url) > $length) {
		$url = str_replace(array('%3A', '%2F'), array(':', '/'), rawurlencode($url));
		$url = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
	}
	return $url;
}

//取数组中的随机个
function sarray_rand($arr, $num=1) {
	$r_values = array();
	if($arr && count($arr) > $num) {
		if($num > 1) {
			$r_keys = array_rand($arr, $num);
			foreach ($r_keys as $key) {
				$r_values[$key] = $arr[$key];
			}
		} else {
			$r_key = array_rand($arr, 1);
			$r_values[$r_key] = $arr[$r_key];
		}
	} else {
		$r_values = $arr;
	}
	return $r_values;
}

//检查邮箱是否有效
function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//检查手机号码是否有效
function ismobile($mobile) {
	return strlen($mobile) > 4 && preg_match("/^[1-9]\d*$/", $mobile);
}

//检查国家区号是否有效
function iscountry($country) {
	return strlen($country) >= 1 && preg_match("/^[1-9]\d*$/", $country);
}

//获取目录
function sreaddir($dir, $extarr=array()) {
	$dirs = array();
	if($dh = opendir($dir)) {
		while (($file = readdir($dh)) !== false) {
			if(!empty($extarr) && is_array($extarr)) {
				if(in_array(strtolower(fileext($file)), $extarr)) {
					$dirs[] = $file;
				}
			} else if($file != '.' && $file != '..') {
				$dirs[] = $file;
			}
		}
		closedir($dh);
	}
	return $dirs;
}

//发送iphone push消息
function push2iphone($body) {
	global $_SGLOBAL, $_CONFIG, $appid;
	$request_appid = $appid;
	$request_body = json_encode($body);
	$request_sign = md5($_CONFIG['appkey_map'][$appid].$request_body);
	$data =  "appid=$appid&sign=$request_sign&body=".urlencode($request_body);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $_CONFIG['push_serverurl']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch,CURLOPT_TIMEOUT,2);
	$response = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
	curl_close($ch);
	api_log("[PUSH] push2iphone url:".$_CONFIG['push_serverurl']." data:".$data." response:".$response);
	if($httpCode < 400){
		return $response;
    }else{
		return "1901"; 
    }
}


//发送短信
function sendSMS($sms_country, $sms_mobile, $sms_message){
	if($sms_country==86){
		return cn_sendSMS($sms_mobile, $sms_message);
	}else{
		return us_sendSMS($sms_country.$sms_mobile, $sms_message);
	}
}

//国内通道发送短信
function cn_sendSMS($sms_mobile, $sms_message){
	$newclient=new SMS();
	if($newclient->ConfNull=="1"){
			$mobile = trim($sms_mobile);
			$gbk_message = iconv("UTF-8", "GBK", $sms_message);
			$time = "";
			$apitype = 3; // $apitype 通道选择 0：默认通道； 2：通道2； 3：即时通道；
			$respxml=$newclient->sendSMS($mobile, $gbk_message, $time, $apitype);
			$code=$newclient->getCode();
			$respArr=$newclient->toArray();
			$mess=$respArr["msg"];
			$smsid=$respArr["idmessage"][0];
			$succnum=$respArr["successnum"][0];
			$succphone=$respArr["successphone"][0];
			$failephone=$respArr["failephone"][0];
			api_log("[SMS] Send SMS success, Code:$code, mobile:$mobile, msg:$sms_message");
			return "0";
		} else {
			api_log("[SMS] Send SMS fail, Code:$code, mobile:$mobile, msg:$sms_message");
			return "1";
		}
}

//国际通道发送短信
function us_sendSMS($sms_mobile, $sms_message){
	$url = 'http://bulksms.vsms.net/eapi/submission/send_sms/2/2.0';
	$msisdn = $sms_mobile;
	$data = 'username=moment4app&password=Moment74&message='.urlencode($sms_message).'&msisdn='.urlencode($msisdn);
	$response = sms_do_post_curl_request($url, $data);
	return $response;
}

function sms_do_post_curl_request($url, $data) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch,CURLOPT_TIMEOUT,2);
	$response = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
	curl_close($ch);
	if($httpCode < 400){ 
		api_log("sms_do_post_curl_request sucess:$url, Data:$data, httpCode:$httpCode, Error:$response");
		return "0"; 
    }else{
		api_log("sms_do_post_curl_request fail:$url, Data:$data, httpCode:$httpCode, Error:$response");
		return "1"; 
    }
}

//记录设备绑定信息
function save_equipment($uid, $id, $imei, $imsi, $bundle_id, $token, $os, $os_version, $model, $app_version, $app_channel) {
	global $_SGLOBAL, $_CONFIG;
	//解绑其他UID
	if($uid>0){
		$sql = "UPDATE equipment SET uid = 0 WHERE uid = '$uid'";
		master_db()->query($sql);
	}
	
	//查询设备ID是否已经保存
	$sql = "SELECT id FROM equipment WHERE id = '$id'";
	$query = master_db()->query($sql);
	$equipment = master_db()->fetch_array($query);
	if(!empty($equipment[id])){
		//更新设备记录
		if($uid>0){
			$sql = "UPDATE equipment SET imei = '$imei', imsi = '$imsi', bundle_id = '$bundle_id', token = '$token', os = '$os', os_version = '$os_version', model = '$model', app_version = '$app_version', app_channel = '$app_channel', uid = '$uid' WHERE id = '$id'";
			master_db()->query($sql);
		}else{
			$sql = "UPDATE equipment SET imei = '$imei', imsi = '$imsi', bundle_id = '$bundle_id', token = '$token', os = '$os', os_version = '$os_version', model = '$model', app_version = '$app_version', app_channel = '$app_channel' WHERE id = '$id'";
			master_db()->query($sql);
		}
	}else{
		//新增设备记录
		$sql = "INSERT INTO equipment (id, imei, imsi, bundle_id, token, os, os_version, model, app_version, app_channel, uid) VALUE ('$id', '$imei', '$imsi', '$bundle_id', '$token', '$os', '$os_version', '$model', '$app_version', '$app_channel', '$uid')";
		master_db()->query($sql);
	}
}

//清除设备绑定信息
function clear_equipment($equipment_id) {
	global $_SGLOBAL, $_CONFIG;
	$sql = "UPDATE equipment SET uid = 0,  friend_discovery_badge = 0, friend_fans_badge = 0, friend_fans_badge = 0, message_im_badge = 0, message_reply_badge = 0 WHERE id = '$equipment_id'";
	$query = master_db()->query($sql);
}

//检查Session合法性
function check_session($apiReq){	
	global $_SGLOBAL, $_CONFIG;
	if($apiReq['session_key'] == md5($apiReq["uid"].$apiReq["expired_time"].$_CONFIG['server_sessionkey'])){
		return true;
	}else{
		return false;
	}
}

//记录用户GPS信息
function save_gps($uid, $lat, $lng) {
	global $_SGLOBAL, $_CONFIG;
	if(!empty($uid) && !empty($lat) && !empty($lng)){
		$sql = "UPDATE user SET live_lat = $lat, live_lng = $lng , live_time = $_SGLOBAL[timestamp] WHERE uid = $uid";
		$query = master_db()->query($sql);
	}
}

//记录用户IM密码
function save_im_password($uid, $session_key, $expired_time) {
	$im_password = substr($expired_time.$session_key, 0, 32);
	$sql = "REPLACE INTO users (username, password) VALUES ('$uid', '$im_password')";
	$query = master_db()->query($sql);
}

/**
* 缩略图主函数
* @param string $src 图片路径
* @param int $w 缩略图宽度
* @param int $h 缩略图高度
* @return mixed 返回缩略图路径
* **/
function resize_jpg($src, $dist, $dist_w, $dist_h)
{
    //获取图片的基本信息
    $info=getimagesize($src);
    $src_w=$info[0]; //获取图片宽度
    $src_h=$info[1]; //获取图片高度

	$src_img=imagecreatefromjpeg($src);
    $dist_img=imagecreatetruecolor($dist_h, $dist_h); //创建画布
    imagecopyresampled($dist_img, $src_img, 0, 0, 0, 0, $dist_w, $dist_h, $src_w, $src_h);
    imagejpeg($dist_img, $dist, 90);
    imagedestroy($src_img);
	imagedestroy($dist_img);
}

//$input - stuff to decrypt
//$key - the secret key to use

function do_mencrypt($input, $key)
{
        $input = str_replace("\n", "", $input);
        $input = str_replace("\t", "", $input);
        $input = str_replace("\r", "", $input);
        $key = substr(md5($key), 0, 24);
        $td = mcrypt_module_open('tripledes', '', 'ecb', '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $encrypted_data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return trim(chop(base64_encode($encrypted_data)));
}
    
//$input - stuff to decrypt
//$key - the secret key to use
    
function do_mdecrypt($input, $key)
{
        $input = str_replace("\n", "", $input);
        $input = str_replace("\t", "", $input);
        $input = str_replace("\r", "", $input);
        $input = trim(chop(base64_decode($input)));
        $td = mcrypt_module_open('tripledes', '', 'ecb', '');
        $key = substr(md5($key), 0, 24);
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $decrypted_data = mdecrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return trim(chop($decrypted_data));
} 